// @ts-ignore
import md5 from 'js-md5'
// @ts-ignore
import CryptoJS from 'crypto-js'

/**
 * js实现签名
 * getUrlVariables、collData、sign
 */
// 获取url参数
export function getUrlVariables(url: any) {
  const data: any = {}
  const idx = url.indexOf('?')
  if (idx < 0) {
    return data
  }
  const query = url.substring(idx + 1)
  const vars = query.split('&')
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split('=')
    data[pair[0]] = pair[1]
  }
  return data
}

// 搜集参数
export function collData(target: any, source: any) {
  const data: any = {}
  // 为了不影响target的值，这里需要手动赋值
  for (const key in target) {
    data[key] = target[key]
  }
  for (const key in source) {
    data[key] = source[key]
  }
  return data
}

// 取出data所有参数并签名
export function sign(ajaxCfg: any) {
  const res: any = {},
    url = ajaxCfg.url,
    urlData = getUrlVariables(url)
  const t = new Date().getTime()
  res.t = t
  const data: any = collData(ajaxCfg.data, urlData)
  const arr = []
  for (const k in data) {
    if (data[k] !== undefined && data[k] !== '') {
      arr.push(k)
    }
  }
  const arrSort = arr.sort()
  let encodeStr = ''
  let ciphertext = ''
  if (arr.length > 0) {
    ciphertext = arr[0] + '=' + data[arr[0]] + '&t=' + t
  } else {
    ciphertext = 't=' + t
  }
  ciphertext = (md5 as unknown as any)(ciphertext)
  for (const e of arrSort) {
    encodeStr += '&' + e + '=' + data[e]
  }
  encodeStr = encodeStr.substr(1)
  encodeStr += '&t=' + t + '&ciphertext=' + ciphertext
  res.sign = (md5 as unknown as any)(encodeStr)
  ajaxCfg.headers = Object.assign(ajaxCfg.headers || {}, res)
}

// pointJson字段加密规则:
// 公共加密函数：
export function aesEncrypt(word: any, keyWord: any) {
  const key = CryptoJS.enc.Utf8.parse(keyWord)
  const srcs = CryptoJS.enc.Utf8.parse(word)
  const encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.toString()
}

// 判断终端
export function getOpenOS() {
  const ua = navigator.userAgent
  return {
    isAndroid: ua.indexOf('Android') > -1 || ua.indexOf('Adr') > -1 //android终端
  }
}

/**
 * h5向app传人机校验成功后返回的票据
 * @param captchaVerification
 */
export function sendCaptchaVerification(captchaVerification: string) {
  if (!getOpenOS().isAndroid) {
    if ((window as any).webkit) {
      ;(window as any).webkit.messageHandlers.sendCaptchaVerification.postMessage({
        captchaVerification: captchaVerification
      })
    }
  } else {
    return (window as any).AppJsObj.sendCaptchaVerification(captchaVerification)
  }
}
